import React, {useState, useRef} from 'react';
import {message, Button, Divider, Popconfirm,Tooltip,Tag} from 'antd';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import {connect} from 'umi';
import {PlusOutlined} from '@ant-design/icons';
import {getOvertimePage,overWorkBpm,deleteOverWorkById,saveOverWork} from '../service';
import {overtimeType} from "@/utils/constant";
import moment from 'moment';
import AddForm from './components/AddForm';

const TableList = () => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [record, setRecord] = useState(null);
  const [title, setTitle] = useState(null);

  const addAndEditOvertime = (record,flag) => {
    if(record){
      setRecord(record);
    }
    setTitle(record ? '编辑' : '新建');
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    setRecord(null);
  };

  const delOvertime = (id) => {
    setLoading(true);
    deleteOverWorkById(id).then(res => {
      if (res.flag) {
        message.success(`删除成功！`);
        actionRef.current.reload();
      } else {
        message.error(`删除失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const sendBpm = (id) => {
    setLoading(true);
    overWorkBpm(id).then(res => {
      if (res.flag) {
        message.success(`bpm发起成功！`);
        window.open(res.data);
      } else {
        message.error(`bpm错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveOverWork(values).then((res) => {
      if (res.flag) {
        handleCancel();
        message.success(`操作保存成功！`);
        actionRef.current.reload();
      } else {
        message.error(`保存失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const columns = [
    {
      title: '申请时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) =>{
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '申请人工号',
      hideInSearch: true,
      dataIndex: 'oprationId',
    },
    {
      title: '加班人员',
      dataIndex: 'subEmployeeOverworkEntities',
      hideInSearch: true,
      align:'center',
      width: 300,
      render:(text)  => (
        <>
          {text?.map((item,index) => {
            let temp = item.corpName + "-" + item.orgName + "-" + item.employeeName + "-" + item.employeeId;
            return  <Tooltip overlayStyle={{maxWidth: 500}} title={temp} key={index}>
              <Tag style={{marginTop:'5px'}} color={'#68b377'} key={index}>
                {item.employeeName}
              </Tag>
            </Tooltip>
          }
          )}
        </>
      )
    },
    {
      title: '加班类型',
      dataIndex: 'overworkType',
      hideInSearch: true,
      render: (text) => {
        return overtimeType.find((item) => item.value === text).label;
      },
    },
    {
      title: '加班开始日期',
      dataIndex: 'overworkBeginTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '加班结束日期',
      dataIndex: 'overworkEndTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '加班状态',
      dataIndex: 'satus',
      valueEnum: {
        1: { text: '待发起', status: 'Default' },
        2: { text: '审批中', status: 'Processing' },
        3: { text: '审批通过', status: 'Success' },
        4: { text: '审批拒绝', status: 'Warning' },
      },
    },
    {
      title: '加班说明',
      dataIndex: 'overworkRemark',
      hideInSearch: true,
      ellipsis:true,
      width: 200
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align:'center',
      render: (item, record) => (
        <>
          {
            (record.satus === 1) && <>
              <a onClick={() => addAndEditOvertime(record,true)}>编辑</a>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认删除?`} onConfirm={() => delOvertime(record.id)} okText="是" cancelText="否">
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical"/>
              <a onClick={() => sendBpm(record.id)}>发起申请</a>
            </>
          }
          {(record.satus !== 1 && record.checkUrl) && <><a onClick={() => window.open(record.checkUrl)}>查看详情</a></>}
        </>
      ),
    }
  ];

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        request={(params) => getOvertimePage(params)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => addAndEditOvertime(null,false)}><PlusOutlined/>新增</Button>,
        ]}
      />
      <AddForm
        loading={loading}
        visible={visible}
        record={record}
        title={title}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};
export default connect(({}) => ({}))(TableList)
